package com.voxel.sense.infomsg.module.task.execution;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.IntentUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.example.com.common.view.dialog.IDialog;
import com.example.com.common.view.dialog.NumbProgressDialog;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.FileImageInfo;
import com.voxel.sense.infomsg.interfaces.listener.onMyItemClickListener;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.FileProvider7;
import com.voxel.sense.infomsg.utils.OpenDocuIntentUtils;
import com.voxel.sense.infomsg.view.MyGridView;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.CommonImagePagerActivity;
import com.voxel.sense.infomsg.widget.adapter.FileGalleryAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnItemClick;
import cn.jzvd.Jzvd;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.MyTaskListInfoEntity;
import cyy.example.com.facotry.share.SPEngine;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.utils.Orientation;

//import com.mabeijianxi.smallvideorecord2.DeviceUtils;
//import com.mabeijianxi.smallvideorecord2.JianXiCamera;
//import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;
//import com.mabeijianxi.smallvideorecord2.model.MediaRecorderConfig;

/**
 * 任务执行上传
 */
public class TaskExecutionActivity extends BViewActivity<TaskExecutionContract.Presenter>
        implements TaskExecutionContract.View {

    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.tv_desc)
    TextView tv_desc; //任务类型描述
    @BindView(R.id.tv_type)
    TextView tv_type;//紧急类型
    @BindView(R.id.tv_firm_name)
    TextView tv_firm_name;//公司名称
    @BindView(R.id.iv_location_icon)
    ImageView iv_location_icon;
    @BindView(R.id.tv_district)
    TextView tv_district; //tv_district区地址
    @BindView(R.id.divider)
    View divider;
    @BindView(R.id.tv_address)
    TextView tv_address; //详细地址
    @BindView(R.id.iv_time_icon)
    ImageView iv_time_icon;
    @BindView(R.id.tv_start_time)
    TextView tv_start_time; //时间
    @BindView(R.id.tv_people_name)
    TextView tv_people_name; //执行人
    @BindView(R.id.tv_pic_tip_desc)
    TextView tv_pic_tip_desc;
    @BindView(R.id.gridview_image)
    MyGridView gridview_image;//图片选择
    @BindView(R.id.gridview_doc)
    MyGridView gridview_doc;//文件选择
    @BindView(R.id.gridview_video)
    MyGridView gridview_video;//视频选择
    @BindView(R.id.tv_video_text_desc)
    TextView tv_video_text_desc; //上传视频的描述文本
    @BindView(R.id.btn_pass)
    Button btn_pass; //提交按钮

    private FileGalleryAdapter mImageAdapter;//图片展示的适配器
    private FileGalleryAdapter mDocuAdapter;//文件展示的适配器
    private FileGalleryAdapter mVideoAdapter;//文件展示的适配器

    private MyTaskListInfoEntity.BodyBean.TaskInfoListBean mBean;
    private long mVideoUploadMaxSize;
    private File mTakePhotoFile;
    private boolean mIsSelecPic;

    NumbProgressDialog mProgressdialog;
    private Dialog mMessageDialog;
    boolean isUploadComplete = false;


    public static void show(Context context, MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean) {
        if (bean == null) {
            return;
        }
        Intent intent = new Intent(context, TaskExecutionActivity.class);
        intent.putExtra(IntentConstants.OBJECT_TYPE, bean);
        context.startActivity(intent);
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_mission_describe;
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }

    @Override
    protected TaskExecutionContract.Presenter initPresenter() {
        return new TaskExecutionPresenter(this);
    }


    @Override
    protected void initWidows() {
        super.initWidows();

    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        mBean = (MyTaskListInfoEntity.BodyBean.TaskInfoListBean) getIntent().getSerializableExtra(IntentConstants.OBJECT_TYPE);
        if (mBean == null) {
            ToastUtil.showToastLong(Factory.app(), "界面跳转发生错误 ");
            finish();
        }
        return super.initArgs(bundle);
    }

    @Override
    protected void initData() {
        super.initData();

        titlebar.setTitleText("任务执行单");
        btn_pass.setText("提交");
        tv_desc.setText(mBean.getTaskType());
        String taskUrgentGrade = mBean.getTaskUrgentGrade();
        if (TextUtils.isEmpty(taskUrgentGrade)) {
            tv_type.setVisibility(View.GONE);
        } else {
            tv_type.setVisibility(View.VISIBLE);
            tv_type.setText(taskUrgentGrade);
        }
        tv_district.setText(mBean.getTaskAreaName());
        tv_address.setText(mBean.getTaskObjectAddress());
        tv_start_time.setText(mBean.getTaskStartTime() + "--" + mBean.getTaskEndTime());
        tv_people_name.setText(mBean.getTaskExcutorName());
        tv_firm_name.setText(mBean.getTaskObject());


        mVideoUploadMaxSize = (SPEngine.getSPEngine().getVideoUploadMaxSize() != 0 ? mVideoUploadMaxSize : 20);
        tv_video_text_desc.setText(String.format(getString(R.string.up_video_text_desc), mVideoUploadMaxSize + "M"));
        initCameraConfig();
        initFileGalleryAdapter();
    }

    private void initFileGalleryAdapter() {
        ArrayList<FileImageInfo> lstImageData = new ArrayList<>();
        ArrayList<FileImageInfo> listDocuData = new ArrayList<>();
        ArrayList<FileImageInfo> listVideoData = new ArrayList<>();

        //添加一个头显示添加图片的样式
        lstImageData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));
        listDocuData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));
        listVideoData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));

        //初始化图片选择模块
        mImageAdapter = new FileGalleryAdapter(this, lstImageData);
        gridview_image.setAdapter(mImageAdapter);

        //初始化文档选择模块
        mDocuAdapter = new FileGalleryAdapter(this, listDocuData);
        mDocuAdapter.setFile_type(Constants.file_docu);
        gridview_doc.setAdapter(mDocuAdapter);

        //初始化视频选择模块
        mVideoAdapter = new FileGalleryAdapter(this, listVideoData);
        mVideoAdapter.setFile_type(Constants.file_vedio);
        mVideoAdapter.setMax_num(1);
        gridview_video.setAdapter(mVideoAdapter);

    }

    /**
     * 初始化视频录制的配置
     */
    private void initCameraConfig() {
        //初始化视频拍摄的配置
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
//        if (DeviceUtils.isZte()) {
//            if (dcim.exists()) {
//                JianXiCamera.setVideoCachePath(dcim + "/mabeijianxi/");
//            } else {
//                JianXiCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
//                        "/sdcard-ext/")
//                        + "/mabeijianxi/");
//            }
//        } else {
//            JianXiCamera.setVideoCachePath(dcim + "/mabeijianxi/");
//        }
//        // 初始化拍摄，遇到问题可选择开启此标记，以方便生成日志
//        JianXiCamera.initialize(false, null);
    }


    @Override
    protected void initEven() {
        super.initEven();
        //提交任务监听
        btn_pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sbumitTask();
            }
        });

        //上传文件移除操作监听
        mImageAdapter.setOnDeleteListener(new onMyItemClickListener() {
            @Override
            public void onItemClick(int posision) {
                mPresenter.removePhotoDatas(posision);
            }
        });
        mVideoAdapter.setOnDeleteListener(new onMyItemClickListener() {
            @Override
            public void onItemClick(int posision) {
                mPresenter.removeVideoDatas(posision);
            }
        });
        mDocuAdapter.setOnDeleteListener(new onMyItemClickListener() {
            @Override
            public void onItemClick(int posision) {
                mPresenter.removeDocDatas(posision);
            }
        });
    }

    /**
     * 提交任务
     */
    private void sbumitTask() {
        //将提交按钮设置不可用，以防重复提交
        btn_pass.setEnabled(false);
        String taskNumber = mBean.getTaskNumber();
//        TaskManagerNetHelper.executeTask(taskNumber, this);
        mPresenter.doSubmitTask(taskNumber);
    }

    /**
     * 列表点击事件
     */
    @OnItemClick({R.id.gridview_image, R.id.gridview_doc, R.id.gridview_video})
    public void gridItemClick(GridView view, View childrenView, int position, long id) {
        switch (view.getId()) {
            case R.id.gridview_image://图片item点击事件
                pickClickEvent(position);
                break;
            case R.id.gridview_doc://文档item点击事件
                docuClickEvent(position);
                break;
            case R.id.gridview_video://视频item点击事件
                videoClickEvent(position);
                break;
        }
    }


    private void videoClickEvent(final int position) {
        if (position == mVideoAdapter.getCount() - 1) {
            //点击最后一个，则是添加图片
            final List<String> list = new ArrayList<>();
            list.add("拍摄");
            list.add("从相册选中");
            DialogImpl.getInstance().showItemDialog(this, "", list, new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (what == 0) {
                        //拍摄
//                        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
//                                .fullScreen(true)
//                                .smallVideoWidth(460)
//                                .smallVideoHeight(600)
//                                .recordTimeMax(1000 * 15)//最大录制时间，单位浩渺
//                                .recordTimeMin(5)//最小录制时间
//                                .maxFrameRate(28)//最大帧率，一定程度上影响视频质量与大小，不要太高，有的低配手机转码速度可能会跟不上
//                                .videoBitrate(600000)//比特率，一定程度上影响视频质量与大小，理论上值越大质量将会越好
//                                .captureThumbnailsTime(1)
//                                .build();
//                        MediaRecorderActivity.goSmallVideoRecorder(TaskExecutionActivity.this, config);
                    } else {
                        addPicOrVideo(false, mVideoAdapter.getDatasPath());

                    }
                }
            });
        } else {
            //播放图片
            IDialog.getInstance().showChooseDialog(this, "", "是否播放视频", new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (IDialog.YES == what) {
                        String filePath = mVideoAdapter.getList().get(position).filePath;
                        Jzvd.startFullscreenDirectly(TaskExecutionActivity.this, Jzvd.class, filePath, "");
                    }

                }
            });
        }
    }

    private void docuClickEvent(int position) {
        if (position == mDocuAdapter.getCount() - 1) {
            //点击最后一个，则是添加图片
            addDoc();
        } else {
            String filePath = mDocuAdapter.getList().get(position).filePath;
            String type = "text/plain";//默认文本类型 查看
            String file = filePath;
            String fileExtension = FileUtils.getFileExtension(file);//获取文件后缀

            if (Constants.EXTENSION_DOC.equals(fileExtension) || Constants.EXTENSION_DOCX.equals(fileExtension)) {
                //doc文档
                type = "application/msword";
            } else if (Constants.EXTENSION_XLS.equals(fileExtension) || Constants.EXTENSION_XLSX.equals(fileExtension)) {
                //xls文档
                type = "application/vnd.ms-excel";
            } else if (Constants.EXTENSION_PDF.equals(fileExtension)) {
                //pdf文档
                type = "application/pdf";
            } else if (Constants.EXTENSION_PPT.equals(fileExtension) || Constants.EXTENSION_PPTX.equals(fileExtension)) {
                //ppt文档
                type = "application/vnd.ms-powerpoint";
            }
            OpenDocuIntentUtils.DocuItent(this, new File(file), type, fileExtension);
        }
    }

    private void pickClickEvent(int position) {
        if (position == mImageAdapter.getCount() - 1) {
            //点击最后一个，则是添加图片
            List<String> list = new ArrayList<>();
            list.add("拍摄");
            list.add("从相册选中");
            DialogImpl.getInstance().showItemDialog(this, "", list, new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (what == 0) {
                        //拍照
                        takePhoto();
                    } else {
                        addPicOrVideo(true, mImageAdapter.getDatasPath());
                    }
                }
            });
        } else {
            ArrayList<String> datasPath = mImageAdapter.getDatasPath();
            //查看图片
            CommonImagePagerActivity.showImages(TaskExecutionActivity.this, datasPath, position);
        }
    }

    private void takePhoto() {
        mTakePhotoFile = new File(AppFileUtil.getPhoneImageDir(),
                TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-ddHHmmss", Locale.getDefault())) + ".jpg");
        Uri uriForFile = FileProvider7.getUriForFile(mTakePhotoFile);
        Intent intent = IntentUtils.getCaptureIntent(uriForFile);
        startActivityForResult(intent, IntentConstants.REQUEST_CODE_TAKE_PHOTO);
    }


    /**
     * 调出图片或视频的选择器
     *
     * @param isPic ture时是选择图片，flase是视频
     */
    private void addPicOrVideo(boolean isPic, ArrayList<String> list) {
        mIsSelecPic = isPic;
        FilePickerBuilder.getInstance().setMaxCount(Constants.UPLOAD_FILE_MAX_COUNT)
                .setSelectedFiles(list)
                .setActivityTheme(R.style.FilePickerTheme)
                .enableImagePicker(isPic)
                .enableVideoPicker(!isPic)//是否能视频图片
                .enableCameraSupport(isPic)//是否有照相item
                .showGifs(false)//是否显示gif图
                .showFolderView(false)//是否显示文件夹
                .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
                .setCameraPlaceholder(R.mipmap.custom_camera)//相机图片
                .withOrientation(Orientation.UNSPECIFIED)
                .pickPhoto(this);//显示文件
    }

    /**
     * 拉起文档选择器
     */
    private void addDoc() {
        String[] docExtensions = {"doc", "docx"};
        String[] pdfExtensions = {".pdf"};
        String[] excelExtensions = {"xls", "xlsx"};
        String[] txtExtensions = {".txt"};
        String PDF = "PDF";
        String DOC = "DOC";
        String XLS = "XLS";
        String TXT = "TXT";
        FilePickerBuilder.getInstance().setMaxCount(Constants.UPLOAD_FILE_MAX_COUNT)
                .setActivityTheme(R.style.FilePickerTheme)
                .setSelectedFiles(mDocuAdapter.getDatasPath())
                .addFileSupport(PDF,pdfExtensions)
                .addFileSupport(DOC,docExtensions)
                .addFileSupport(XLS,excelExtensions)
                .addFileSupport(TXT,txtExtensions)
                .showFolderView(false)//是否显示文件夹
                .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
                .withOrientation(Orientation.UNSPECIFIED)
                .pickFile(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FilePickerConst.REQUEST_CODE_PHOTO://图片及选择回调
                    if (data != null) {
                        getSelectPicOrVideoResult(data);
                    }
                    break;
                case FilePickerConst.REQUEST_CODE_DOC: //文档选择回调
                    if (data != null) {
                        getSelectDocuResult(data);
                    }
                    break;
                case IntentConstants.REQUEST_CODE_TAKE_PHOTO://拍照回调
                    getPickPhoneResult();
                    break;
//                case MediaRecorderActivity.start_request://拍摄回调
//                    getTakeVideoResult(data);
//                    break;
            }
        }
    }

    private void getTakeVideoResult(Intent data) {
//        String VideoUrl = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
//        //视频类型
//        if (!TextUtils.isEmpty(VideoUrl) && FileUtils.isFileExists(VideoUrl)) {
//            ArrayList<String> bean = new ArrayList();
//            bean.add(VideoUrl);
//            mPresenter.doDisposeVideoDatas(bean);
//            mVideoAdapter.notifyDataSetChanged();
//        }
    }

    private void getPickPhoneResult() {
        if (FileUtils.isFileExists(mTakePhotoFile)) {
            Intent borad = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            borad.setData(Uri.fromFile(mTakePhotoFile));
            sendBroadcast(borad);
            mPresenter.doTakePhotoFinish(mTakePhotoFile);
        } else {
            ToastUtil.showToastLong(Factory.app(), "获取拍摄照片失败");
        }
    }

    private void getSelectDocuResult(Intent data) {
        ArrayList<String> bean = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS);
        mPresenter.doDisposeDocData(bean);
    }

    private void getSelectPicOrVideoResult(Intent data) {
        if (mIsSelecPic) {//图片类型
            ArrayList<String> datas = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
            mPresenter.doLoadGalleryData(datas);

        } else {
            //视频类型
            ArrayList<String> datas = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
            mPresenter.doDisposeVideoDatas(datas);

        }
    }

    /**
     * 上传动作完成后，刷新界面
     */
    private void UpComplateFresh() {
        isUploadComplete = true;
        mDocuAdapter.setUpComplate(true);
        mImageAdapter.setUpComplate(true);
        mVideoAdapter.setUpComplate(true);
        titlebar.setRightText("");
        dismissProgressDialog();
        if (mMessageDialog != null) {
            mMessageDialog.dismiss();
        }
        if (mProgressdialog != null) {
            mProgressdialog.dismiss();
        }

        //发送通知，外层列表改变状态
        EventBus.getDefault().post(new EventEntity(
                EventBusConstants.TASK_ACTION_FINISH, mBean.getTaskNumber()));
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onRefreshPhoto(ArrayList datas) {
        mImageAdapter.setList(datas);
    }

    @Override
    public void onRefreshDoc(ArrayList datas) {
        mDocuAdapter.setList(datas);
    }

    @Override
    public void onRefreshVideo(ArrayList datas) {
        mVideoAdapter.setList(datas);
    }

    @Override
    public void onUpLoadComeplete() {
        UpComplateFresh();
        IDialog.getInstance().showMessageDialog(TaskExecutionActivity.this, "", "任务提交成功", new DialogCallBack() {
            @Override
            public void onClick(int what) {
            }
        });
    }

    @Override
    public void onUpLocadFailure() {
        isUploadComplete = true;
        //TODO:由于目前终止上传，服务器任务状态也变为已执行，不能再提交任务，暂时也更新ui为完成状态
        UpComplateFresh();
    }

    @Override
    public void showUpLoadProgress(int progress, String msg) {
        if (mProgressdialog == null) {
            mProgressdialog = (NumbProgressDialog) DialogImpl.getInstance().shownNumberProgressDialog(TaskExecutionActivity.this, msg, 1000);
            progressListener();
        }
        mProgressdialog.setCurrentProgress(progress);
        mProgressdialog.setTitle(msg);
    }

    @Override
    public void setUpLoadProgress(int progress) {
        if (mProgressdialog != null) {
            mProgressdialog.setCurrentProgress(progress);
        }
    }

    private void progressListener() {
        mProgressdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(final DialogInterface dialogInterface) {
                //当窗口消失时，需要判断上传是否完全结束
                //1.完成结束了，那么无需任何处理
                //2.没有结束，则需要弹出一个警告，告诉用户是否需要停止上传
                if (isUploadComplete) {
                    return;
                }
                if (mMessageDialog == null && !isFinishing()) {
                    mMessageDialog = DialogImpl.getInstance().showChooseDialog(
                            TaskExecutionActivity.this, "", "是否停止上传,取消任务执行单", "确定", "继续上传", new DialogCallBack() {
                                @Override
                                public void onClick(int what) {
                                    if (what == IDialog.CANCEL) {
                                        //停止上传
                                        mPresenter.doCancleUpLoad();
                                        mMessageDialog.dismiss();
                                        //TODO:由于目前终止上传，服务器任务状态也变为已执行，不能再提交任务，暂时将提交按钮设置为不可用
                                        btn_pass.setEnabled(false);
                                    } else {
                                        //继续上传
                                        if (mProgressdialog != null && !isFinishing()) {
                                            mProgressdialog.show();
                                        }
                                        mMessageDialog.dismiss();
                                    }
                                }
                            });
                    mMessageDialog.setCancelable(false);
                    mMessageDialog.setCanceledOnTouchOutside(false);
                } else if (!isFinishing()) {
                    mMessageDialog.show();
                }
            }
        });
    }
}
